package cn.edu.lzzy.controllers.admin;

import cn.edu.lzzy.entities.Allocation;
import cn.edu.lzzy.entities.Course;
import cn.edu.lzzy.entities.Messages;
import cn.edu.lzzy.entities.User;
import cn.edu.lzzy.services.AllocationService;
import cn.edu.lzzy.services.CourseService;
import cn.edu.lzzy.services.UserService;
import cn.edu.lzzy.utils.AuthUtils;
import cn.edu.lzzy.utils.StringUtils;
import cn.edu.lzzy.vm.JSONResult;
import cn.edu.lzzy.vm.VmCourse;

import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.oas.annotations.EnableOpenApi;


import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/***
 * 课程业务
 * 包含新增课程、更新课程、删除课程、查询教师建课信息业务操作
 */
@CrossOrigin
@RestController
@EnableOpenApi
@Tag(name = "course-api-controller",description = "课程接口实现")
public class CourseApiController {
    private  final CourseService courseService;
    private final UserService userService;
    private  final AllocationService allocationService;

    public CourseApiController(CourseService courseService, UserService userService, AllocationService allocationService) {
        this.courseService = courseService;
        this.userService = userService;
        this.allocationService = allocationService;
    }



    @Operation(summary = "获取课程")
    @Parameters(@Parameter(description = "getCourse"))
    @GetMapping(value = "/course/")
    public JSONResult getCourse(@Parameter(description = "用户token值",required = true ) @RequestParam String token){
    List<VmCourse> courses=new ArrayList<>();
    courseService.getCourse().forEach(course ->courses.add(VmCourse.create(course,false)));
     return new JSONResult(200,courses,courses.size()+"");
    }

    //查询分页课程信息
    @Operation(summary = "查询分页课程信息")
    @Parameters(@Parameter(description = "getPagedCourse"))
    @GetMapping(value = "/course/page")
    public JSONResult getPagedCourse(@RequestParam String token,@RequestParam int page,@RequestParam int size){
        List<VmCourse> courses=new ArrayList<>();
        courseService.getCourseByPage(page,size).forEach(caurse ->courses.add(VmCourse.create(caurse,false)));

        return new JSONResult(200,courses,courseService.count()+"");
    }



    //老师
    @Operation(summary = "查询教师建课信息")
    @Parameters(@Parameter(description = "getTeachersCourse"))
    @GetMapping(value = "/course/teacher")
    public JSONResult getTeacherCourses(@RequestParam String token,@RequestParam(name="id") UUID teacherId){
        List<VmCourse> courses=new ArrayList<>();
        courseService.getTeachersCourse(teacherId).forEach(course -> courses.add(VmCourse.create(course,true)));

        return new JSONResult(200,courses,courses.size()+"");
    }



    //查询学生选课信息
    @Operation(summary = "查询学生选课信息")
    @Parameters(@Parameter(description = "getStudentCourse"))
    @GetMapping(value = "/course/student")
    public JSONResult getStudentCourse(@RequestParam String token,@RequestParam UUID studentId){
        List<VmCourse> courses=new ArrayList<>();
        courseService.getStudentsCourse(studentId).forEach(course -> courses.add(VmCourse.create(course,false)));
        return new JSONResult(200,courses,courses.size()+"");
    }


   private  JSONResult addOrUpdate(UUID id, JSONObject json){
        String token=json.getString("token");
        String courseName=json.getString("name");
       String desc=json.getString("desc");
       String cover=json.getString("cover");
       boolean isOpen=json.getBoolean("open");
       String teacherId=json.getString("teacherId");
       if(StringUtils.isEmpty(courseName)||StringUtils.isEmpty(desc)||StringUtils.isEmpty(cover)||StringUtils.isEmpty(teacherId) ){
           return new JSONResult(404,null,Messages.INCOMPLETE_INFO.toString());
       }
       User teacher=userService.getById(UUID.fromString(teacherId));
       if(teacher==null)
           return new JSONResult(404,null,Messages.INCOMPLETE_INFO.toString());
       Course course;
       boolean createStatus=(id==null);
       if(createStatus){
           course=new Course();
           course.setTeacher(teacher);
       }else {
           course=courseService.getCourseById(id);
           if(course==null){
              return new JSONResult(404,null,Messages.INCOMPLETE_INFO.toString());
           }
           course.setOpen(isOpen);
          course.setName(courseName);


           /////...

           if(createStatus)
               return JSONResult.isOk(VmCourse.create(courseService.add(course),true),Messages.SUCCESS.toString());
           else{
               Course update=courseService.update(course,token);
               if(update==null)
                   return new JSONResult(404,null,Messages.INVALID_FORMAT.toString());
           }
       }
        return null;
   }

    @Operation(summary = "新增课程")
    @Parameters(@Parameter(description = "add"))
    @GetMapping(value = "/course/add")
    public JSONResult add( @RequestBody JSONObject json){
         return  addOrUpdate(null,json);
    }

    //修改
    @Operation(summary = "更新课程")//需要教师，管理员角色
//    @Parameters(@Parameter(description = "ddd"))
    @GetMapping(value = "/course/update/{id}",produces = "application/json")
    public JSONResult update(@PathVariable UUID id, @RequestBody JSONObject json){
        String token=json.getString("token");
        Allocation allocation= allocationService.findAllocation("/api/v1/course/put/{id}");//
        int[] roles= AuthUtils.getRoles(allocation.getRoles()).stream().mapToInt(r ->r).toArray();
        if(AuthUtils.illegalUser(token,roles)){
            return new JSONResult(403,"限制访问（自定义访问控制）",Messages.NO_PERMISSION.toString());
        }
        return addOrUpdate(id,json);

    }


    //删除
    @Operation(summary = "删除课程")
    @Parameters(@Parameter(description = "delete"))
    @GetMapping(value = "/course/remove")
    public JSONResult delete( @RequestBody JSONObject json){
        String token=json.getString("token");
        String strCourseId=json.getString("courseId");
        if(StringUtils.isEmpty(token)||StringUtils.isEmpty(strCourseId)){
            return new JSONResult(400,null,Messages.INCOMPLETE_INFO.toString());
        }
        try{
            return new JSONResult(200,null,"生成删除对象的消息");
        }catch (Exception ex){
            return new JSONResult(400,ex.getMessage(),Messages.WRONG_ID.toString());
        }

    }


}
